<template>
  <div class="body">
    <div class="table-wrap">
      <div class="search_header">
        <span>
          <el-button
            v-has="'mapManagement:add'"
            icon="el-icon-plus"
            @click="
              ;(dialogVisible = true),
                (add = true),
                (headerTitle = '新增底图')
            "
            >新增底图
          </el-button>
        </span>
        <div class="search_header_right">
          <el-input
            placeholder="请输入底图名称"
            @change="searchMap"
            v-model="query.name"
          >
            <span
              @click="searchMap"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
        </div>
        <!-- <el-select
          v-model="query.serviceType"
          clearable
          @change="searchMap"
        >
          <el-option
            v-for="item in formData"
            :key="item.name"
            :label="item.name"
            :value="item.value"
          />
        </el-select> -->
      </div>
      <el-table
        :data="mapList"
        :header-cell-style="{
          background: '#F2F6FB ',
          color: ' #6B767D'
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          label="底图名称"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column label="缩略图">
          <template slot-scope="scope">
            <el-image
              alt=""
              :src="
                scope.row.filePath
                  ? staticFileUrl +
                    scope.row.filePath.substring(
                      scope.row.filePath.indexOf(
                        '/upload/'
                      ) +
                        '/upload/'.length -
                        1
                    )
                  : ''
              "
              style="height: 45px; width: 45px"
            >
              <div slot="error" class="image-slot">
                <div></div>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <!-- <el-table-column
            label="服务地址"
            prop="serviceUrl"
            show-overflow-tooltip
          /> -->
        <el-table-column
          label="历史影像数据数量"
          prop="serviceCount"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="updateTime"
          show-overflow-tooltip
        />
        <!-- <el-table-column
            label="数据类型"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ funtypeFun(scope.row.serviceType) }}
            </template>
          </el-table-column> -->
        <!--          <el-table-column label="是否为默认">-->
        <!--            <template slot-scope="scope">-->
        <!--              <el-switch-->
        <!--                v-model="scope.row.isDefault"-->
        <!--                style="margin-left: 20px"-->
        <!--                disabled-->
        <!--                :active-value="1"-->
        <!--                :inactive-value="0"-->
        <!--              />-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="Update(scope.row)"
              style="color: #00baff; font-weight: 400"
              v-has="'mapManagement:edit'"
              >编辑
            </el-button>
            <el-button
              type="text"
              @click="deleteRole(scope.row)"
              style="color: #ff5b5b; font-weight: 400"
              v-has="'mapManagement:delete'"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination" v-if="total">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="query.pageSize"
          @current-change="pageChange"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      @close="onClose"
      :title="headerTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="620px"
      top="5vh"
    >
      <el-form
        :model="addList"
        :rules="rules"
        label-width="80px"
        ref="ruleForm"
      >
        <el-form-item label="底图名称" prop="name">
          <el-input v-model="addList.name" clearable />
        </el-form-item>
        <!--        <el-form-item label="是否默认">-->
        <!--          <el-switch-->
        <!--            v-model="addList.isDefault"-->
        <!--            style="margin-left: 20px"-->
        <!--            :active-value="1"-->
        <!--            :inactive-value="0"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="缩略图">
          <el-upload
            action="#"
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <el-image
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            >
              <div slot="error" class="image-slot">
                <div></div>
              </div>
            </el-image>
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            />
          </el-upload>
        </el-form-item>
        <el-tabs
          v-model="editableTabsValue"
          editable
          @edit="handleTabsEdit"
        >
          <el-tab-pane
            :key="item.name"
            v-for="item in editableTabs"
            :label="item.title"
            :name="item.name"
          >
          </el-tab-pane>
        </el-tabs>
        <el-form-item label="数据名称" prop="serviceName">
          <el-input
            v-model="addList.serviceName"
            clearable
          />
        </el-form-item>
        <el-form-item label="服务地址" prop="serviceUrl">
          <el-input
            v-model="addList.serviceUrl"
            clearable
          />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select
            v-model="addList.serviceType"
            clearable
          >
            <el-option
              v-for="item in formData"
              :key="item.name"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地形地址" prop="terrainUrl">
          <el-input
            v-model="addList.terrainUrl"
            clearable
          />
        </el-form-item>
        <el-form-item label="是否默认">
          <el-switch
            v-model="addList.isDefaultData"
            style="margin-left: 20px"
            :active-value="1"
            :inactive-value="0"
            @change="changeData"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onClose">取消</el-button>
        <el-button
          type="primary"
          @click="onSumbit('ruleForm')"
          >确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadImage,
  mapQuery,
  mapInsert,
  mapUpdate,
  mapDelete,
  mapServiceAdd,
  mapServiceDelete,
  mapServiceUpdate,
  mapServiceQuery
} from '@/api/map'
import Icon from '@/components/icon'
import { STATIC_FILE_URL } from '@/api/config.js'

export default {
  name: 'index',
  components: {
    Icon
  },
  data() {
    return {
      mapList: [],
      imageUrl: '',
      addList: {
        name: '',
        serviceName: '',
        serviceUrl: '',
        terrainUrl: '',
        isDefault: 0,
        serviceType: '',
        // terrainType:'',
        isDefaultData: 0,
        fileId: ''
      },
      formData: [
        {
          name: 'WMTS',
          value: 21
        },
        // {
        //   name: 'XYZ_Tiles',
        //   value: 22
        // },
        {
          name: '矢量切片服务',
          value: 23
        },
        {
          name: 'WMS',
          value: 24
        },
        {
          name: 'ArcGIS',
          value: 25
        },
        {
          name: 'REST 服务',
          value: 26
        },
        {
          name: 'RealSpace 服务',
          value: 27
        },
        {
          name: '天地图',
          value: 28
        }
      ],
      pkid: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入底图名称',
            trigger: 'blur'
          }
        ],
        serviceName: [
          {
            required: true,
            message: '请输入数据名称',
            trigger: 'blur'
          }
        ],
        serviceUrl: [
          {
            required: true,
            message: '请输入底图地址',
            trigger: 'blur'
          }
        ],
        serviceType: [
          {
            required: true,
            message: '请选则底图的数据类型',
            trigger: 'change'
          }
        ]
      },
      query: {
        pageSize: 10,
        pageIndex: 1,
        serviceType: '',
        name: ''
      },
      total: '',
      headerTitle: '新增底图',
      add: true,
      dialogVisible: false,
      editableTabsValue: '1',
      editableTabs: [],
      tabIndex: 1,
      resourceMapBaseServiceInfos: []
    }
  },
  mounted() {
    this.getList()
  },
  watch: {
    editableTabsValue(newVal, oldVal) {
      if (this.dialogVisible) {
        // if(this.pkid){
        //   let data=JSON.parse(JSON.stringify(this.resourceMapBaseServiceInfos[oldVal-1]))
        //   data.serviceName=this.addList.serviceName
        //   data.serviceUrl=this.addList.serviceUrl
        //   data.serviceType=this.addList.serviceType
        //   data.terrainUrl=this.addList.terrainUrl
        //   data.terrainType=this.addList.terrainUrl
        //   data.isDefault=this.addList.isDefaultData
        //   // data.orderIndex=oldVal
        //   // if(data.pkid){
        //   //   this.updateMapService(data)
        //   // }else{
        //   //   this.addMapService(data)
        //   // }
        // }else{
        const data =
          this.resourceMapBaseServiceInfos[oldVal - 1]
        data.serviceName = this.addList.serviceName
        data.serviceUrl = this.addList.serviceUrl
        data.serviceType = this.addList.serviceType
        data.terrainUrl = this.addList.terrainUrl
        // data.terrainType=this.addList.terrainUrl
        data.isDefault = this.addList.isDefaultData
        const data1 =
          this.resourceMapBaseServiceInfos[newVal - 1]
        this.addList.serviceName = data1.serviceName
        this.addList.serviceUrl = data1.serviceUrl
        this.addList.serviceType = data1.serviceType
        this.addList.terrainUrl = data1.terrainUrl
        this.addList.isDefaultData = data1.isDefault
        // }
      }
    },
    dialogVisible() {
      this.editableTabsValue = '1'
      this.tabIndex = 1
      this.resourceMapBaseServiceInfos = [
        {
          serviceName: '',
          serviceType: '',
          serviceUrl: '',
          // terrainType:"",
          terrainUrl: '',
          orderIndex: 1,
          isDefault: 1
        }
      ]
      this.addList = {
        name: '',
        serviceName: '',
        serviceUrl: '',
        terrainUrl: '',
        isDefault: 0,
        serviceType: '',
        // terrainType:'',
        isDefaultData: 1,
        fileId: ''
      }
      this.editableTabs = [
        {
          title: '数据1',
          name: '1'
        }
      ]
    }
  },
  computed: {
    staticFileUrl() {
      return STATIC_FILE_URL
    }
  },
  methods: {
    // table展示数据类型名称
    // funtypeFun(funType) {
    //   return this.formData.filter(
    //     (item) => item.value === funType
    //   )[0].name
    // },
    changeData() {
      if (this.addList.isDefaultData) {
        this.resourceMapBaseServiceInfos =
          this.resourceMapBaseServiceInfos.map((item) => {
            item.isDefault = 0
            return item
          })
        this.resourceMapBaseServiceInfos[
          this.editableTabsValue - 1
        ].isDefault = 1
      } else {
        this.resourceMapBaseServiceInfos[0].isDefault = 1
      }
    },
    getMapInfo(id) {
      mapServiceQuery(id).then((res) => {
        if (res.success) {
          // this.addList=res.data
          this.addList.pkid = res.data.pkid
          this.addList.name = res.data.name
          this.addList.isDefault = res.data.isDefault
          this.addList.fileId = res.data.fileId
          // this.resourceMapBaseServiceInfos=res.data.resourceMapBaseServiceInfos
          this.editableTabs = []
          this.resourceMapBaseServiceInfos =
            res.data.resourceMapBaseServiceInfos
              .sort((a, b) => a.orderIndex - b.orderIndex)
              .map((item, index) => {
                // item.orderIndex=(index+1)
                this.editableTabs.push({
                  title: '数据' + (index + 1),
                  name: (index + 1).toString()
                })
                return item
              })
          this.tabIndex =
            this.resourceMapBaseServiceInfos.length
          console.log(this.resourceMapBaseServiceInfos)
          // this.editableTabsValue='1'
          var data =
            this.resourceMapBaseServiceInfos[
              Number(this.editableTabsValue) - 1
            ]
          this.addList.serviceName = data.serviceName
          this.addList.serviceUrl = data.serviceUrl
          this.addList.serviceType = data.serviceType
          this.addList.terrainUrl = data.terrainUrl
          this.addList.isDefaultData = data.isDefault
        } else {
          this.$message.error(res.message)
        }
      })
    },
    deleteMapService(id) {
      this.$confirm(
        '此操作将永久删除该数据服务，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then((e) => {
        mapServiceDelete(id).then((res) => {
          if (res.success) {
            this.$message.success(res.data)
            this.getMapInfo(this.pkid)
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    updateMapService(data) {
      mapServiceUpdate(data, data.pkid).then((res) => {
        if (res.success) {
          // this.$message.success(res.data)
          // this.getMapInfo(this.pkid)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    addMapService(data) {
      mapServiceAdd(data).then((res) => {
        if (res.success) {
          this.$message.success(res.data)
          // this.getMapInfo(this.pkid)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 编辑
    Update(item) {
      this.add = false
      this.pkid = item.pkid
      // this.addList.serviceUrl = item.serviceUrl
      // this.addList.terrainUrl = item.terrainUrl
      // this.addList.serviceName = item.serviceName
      // this.addList.name = item.name
      // this.addList.isDefault = item.isDefault
      // this.addList.fileId = item.fileId
      this.imageUrl = item.filePath
      // this.addList.serviceType = item.serviceType
      this.headerTitle = '编辑底图'
      this.dialogVisible = true
      this.getMapInfo(item.pkid)
    },
    // 删除
    deleteRole(item) {
      this.$confirm(
        '此操作将永久删除该数据，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          mapDelete(item.pkid).then((res) => {
            if (res.success) {
              this.$message.success(res.data)
              this.getList()
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    searchMap() {
      this.query.pageIndex = 1
      this.getList()
    },
    pageChange(page) {
      this.query.pageIndex = page
      this.getList()
    },
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        const newTabName = ++this.tabIndex + ''
        this.editableTabs.push({
          title: '数据' + newTabName,
          name: newTabName
        })
        this.editableTabsValue = newTabName
        this.resourceMapBaseServiceInfos.push({
          serviceName: '',
          serviceType: '',
          serviceUrl: '',
          // terrainType:"",
          terrainUrl: '',
          orderIndex: this.tabIndex,
          isDefault: 0
        })
      }
      if (action === 'remove') {
        if (this.editableTabs.length === 1) {
          this.$message.error('必须保留一条数据！')
          this.tabIndex = 1
          return
        }
        const tabs = this.editableTabs
        const dataList = this.resourceMapBaseServiceInfos
        const pkid = dataList[Number(targetName) - 1].pkid
        let activeName = this.editableTabsValue
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              const nextTab =
                tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        if (pkid) {
          this.$confirm(
            '此操作将永久删除该数据服务，是否继续?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              mapServiceDelete(pkid).then((res) => {
                if (res.success) {
                  this.$message.success(res.data)
                  if (
                    this.total % 10 === 1 &&
                    this.query.pageIndex ===
                      parseInt(this.total / 10) + 1 &&
                    this.query.pageIndex !== 1
                  ) {
                    this.query.pageIndex -= 1
                  }
                  this.getMapInfo(this.pkid)
                } else {
                  this.$message.error(res.message)
                }
              })
              this.editableTabs = tabs.filter(
                (tab) => tab.name !== targetName
              )
              this.editableTabs = this.editableTabs.map(
                (item, index) => {
                  item.title = '数据' + (index + 1)
                  item.name = (index + 1).toString()
                  return item
                }
              )
              this.tabIndex = this.editableTabs.length
              this.editableTabsValue =
                this.tabIndex.toString()
            })
            .catch(() => {})
        } else {
          const currentIndex =
            Number.parseInt(targetName) - 1
          this.resourceMapBaseServiceInfos.splice(
            currentIndex,
            1
          )
          this.editableTabs = tabs.filter(
            (tab) => tab.name !== targetName
          )
          this.editableTabs = this.editableTabs.map(
            (item, index) => {
              item.title = '数据' + (index + 1)
              item.name = (index + 1).toString()
              return item
            }
          )
          this.tabIndex = this.editableTabs.length
          this.editableTabsValue = this.tabIndex.toString()
        }
      }
    },
    // onClose
    onClose() {
      this.dialogVisible = false
      this.addList.serviceName = ''
      this.addList.serviceUrl = ''
      this.addList.isDefault = 0
      this.addList.serviceType = ''
      // this.addList.serviceOrderIndex = ''
      // this.addList.baseOrderIndex = ''
      this.addList.fileId = ''
      this.pkid = ''
      this.imageUrl = ''
      this.getList()
    },
    // 添加
    onSumbit(ruleForm) {
      this.$refs[ruleForm].validate((vaild) => {
        if (vaild) {
          const data =
            this.resourceMapBaseServiceInfos[
              Number(this.editableTabsValue) - 1
            ]
          data.serviceName = this.addList.serviceName
          data.serviceUrl = this.addList.serviceUrl
          data.serviceType = this.addList.serviceType
          data.terrainUrl = this.addList.terrainUrl
          // data.terrainType=this.addList.terrainUrl
          data.isDefault = this.addList.isDefaultData
          var list =
            this.resourceMapBaseServiceInfos.filter(
              (item) => {
                return (
                  !item.serviceName ||
                  !item.serviceUrl ||
                  !item.serviceUrl
                )
              }
            )
          if (list.length) {
            this.$message.error('底图所属数据有必填项未填')
            return
          }
          if (this.add) {
            this.addList.resourceMapBaseServiceInfos =
              this.resourceMapBaseServiceInfos
            mapInsert(this.addList).then((res) => {
              if (res.success) {
                this.$message.success('新增底图成功')
                this.onClose()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            mapUpdate(this.addList, this.pkid).then(
              (res) => {
                if (res.success) {
                  this.$message.success(res.data)
                  if (
                    this.resourceMapBaseServiceInfos.length
                  ) {
                    this.resourceMapBaseServiceInfos.forEach(
                      (item) => {
                        if (item.pkid) {
                          this.updateMapService(item)
                        } else {
                          item.mapBaseId = this.addList.pkid
                          this.addMapService(item)
                        }
                      }
                    )
                  }
                  this.onClose()
                } else {
                  this.$message.error(res.message)
                }
              }
            )
          }
        }
      })
    },
    getList() {
      mapQuery(this.query).then((res) => {
        if (res.success) {
          this.mapList = res.data.list
          this.total = res.data.count
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getFileType(name) {
      const startIndex = name.lastIndexOf('.')
      if (startIndex !== -1) {
        return name.slice(startIndex + 1).toLowerCase()
      } else {
        return ''
      }
    },
    // 上传
    beforeUpload(file) {
      const suffix = this.getFileType(file.name) // 获取文件后缀名
      const suffixArray = ['png', 'jpg'] // 限制的文件类型，根据情况自己定
      if (suffixArray.indexOf(suffix) === -1) {
        this.$message({
          message: '文件格式错误',
          type: 'error',
          duration: 2000
        })
        return false
      }
      const image = new FormData()
      image.append('file', file)
      uploadImage(image).then((res) => {
        if (res.success) {
          this.addList.fileId = res.data
          this.getBase64(file).then((res) => {
            this.imageUrl = res
            console.log(this.imageUrl)
          })
        } else {
          this.$message.error(res.message)
        }
      })
      return false
    },
    // base64转换
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/table.scss';
.body ::v-deep {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .light {
    background: #f9fcff;
    border: 1px solid #f2f6fb !important;
  }

  .body_main_header {
    .el-select {
      float: right;
      margin-right: 10px;
    }

    .el-button {
      background: #497fa3 !important;
      color: white !important;
      border: none !important;
      border-radius: 2px;
    }

    .el-input {
      width: 300px !important;
      float: right;

      .el-button {
        background: #f5f7fa !important;
        color: #a9acb1 !important;
      }
    }
  }

  .el-tabs__item:focus.is-active {
    box-shadow: none !important;
  }

  .el-dialog {
    .el-dialog__header {
      background: #597182 !important;
      padding: 8px 0 14px 24px !important;
      height: 39px !important;

      .el-dialog__title {
        font-size: 16px !important;
        line-height: 22px;
        font-weight: 400 !important;
        color: white !important;
        //margin:19px 0 14px 24px !important;
      }

      .el-dialog__headerbtn {
        font-size: 16px;
        top: 10px !important;
        right: 17px !important;
        color: white !important;

        .el-dialog__close {
          color: white !important;
        }
      }
    }

    .el-dialog__body {
      padding: 17px 32px 18px 26px !important;

      .el-form-item {
        margin-bottom: 19px !important;
      }

      .el-tabs {
        // 居中
        //&__nav-scroll {
        //  width: 50%;
        //  margin: 0 auto;
        //}

        //&__header {
        //  margin-left: 20px;
        //}

        &__nav-wrap::after {
          position: static !important;
        }

        &__active-bar {
          background-color: #497fa3;
          width: 30px !important;
          // margin-left: 10px;
        }

        &__item {
          &.is-active {
            color: #497fa3;
          }

          &:not(:last-of-type) {
            &:after {
              content: '';
              height: 30%;
              width: 1px;
              position: absolute;
              right: 0;
              top: 35%;
              background-color: #d0d8e1;
            }
          }
        }
      }
    }

    .el-input__inner {
      //height: 34px !important;
      background-color: #f6f9fc !important;
    }

    .el-button--default {
      border-color: #497fa3 !important;

      span {
        color: #497fa3 !important;
      }
    }

    .el-button--primary {
      background: #497fa3 !important;
      border-color: white !important;
    }
  }
}
</style>
